﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.ArmyNeedsSuppliesIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class ArmyNeedsSuppliesIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency ArmyNeedsSuppliesIssueFrequency = IssueBase.IssueFrequency.VeryCommon;
    private const float QuestDurationInDays = 15f;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssue), IssueBase.IssueFrequency.VeryCommon));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private bool ConditionsHold(Hero issueGiver)
    {
      return issueGiver.IsLord && issueGiver.MapFaction.IsKingdomFaction && issueGiver.PartyBelongedTo != null && issueGiver.PartyBelongedTo.Army != null && issueGiver.PartyBelongedTo.Army.ArmyOwner == issueGiver && (double) issueGiver.PartyBelongedTo.Army.Cohesion > 80.0;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssue(issueOwner);
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    public class ArmyNeedsSuppliesIssue : IssueBase
    {
      [SaveableField(70)]
      private int NumberOfManInArmy;

      internal static void AutoGeneratedStaticCollectObjectsArmyNeedsSuppliesIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      internal static object AutoGeneratedGetMemberValueNumberOfManInArmy(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssue) o).NumberOfManInArmy;
      }

      private int GrainAmount => MathF.Ceiling((float) (this.NumberOfManInArmy / 20) * 5f);

      private int LiveStockAmount => MathF.Ceiling((float) (this.NumberOfManInArmy / 20) * 0.5f);

      private int WineAmount => MathF.Ceiling((float) (this.NumberOfManInArmy / 20) * 0.5f);

      public override bool IsThereAlternativeSolution => false;

      public override bool IsThereLordSolution => false;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return new TextObject("{=BW7v0g6q}We are about to go on campaign but my quartermaster reports that our food supplies will not be enough to keep us in the field for very long. I can't spare any of my lords, so I need someone else to bring us a large amount of supplies as soon as possible. Can you do this?[if:convo_grave][ib:closed]");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=YaZc08oa}I can bring supplies, your {?QUEST_GIVER.GENDER}ladyship{?}lordship{\\?}. Just tell me what you need.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=444rcko0}We need {GRAIN_AMOUNT} sacks of grain to meet our basic needs. And if you can find {LIVESTOCK_AMOUNT} live stocks and {WINE_AMOUNT} barrels of wine that would be a great favor. Men fight better after a good meal.");
          explanationByIssueGiver.SetTextVariable("GRAIN_AMOUNT", this.GrainAmount);
          explanationByIssueGiver.SetTextVariable("LIVESTOCK_AMOUNT", this.LiveStockAmount);
          explanationByIssueGiver.SetTextVariable("WINE_AMOUNT", this.WineAmount);
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=ppO0hoT6}I'll deliver {GRAIN_AMOUNT} sacks of grain as soon as possible {?QUEST_GIVER.GENDER}lady{?}sir{\\?}, and try to find some livestock and wine as you requested.");
          parent.SetTextVariable("GRAIN_AMOUNT", this.GrainAmount);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject Title => new TextObject("{=wVyqTlpS}Army Needs Supply");

      public override TextObject Description
      {
        get
        {
          TextObject description = new TextObject("{=iMq7M0bo}{QUEST_GIVER.LINK} asks you to provide them supplies for their military campaign.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject);
          return description;
        }
      }

      public ArmyNeedsSuppliesIssue(Hero issueOwner)
        : base(issueOwner, CampaignTime.DaysFromNow(15f))
      {
        this.NumberOfManInArmy = this.IssueOwner.PartyBelongedTo.Army.TotalRegularCount;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(15f), this.RewardGold, this.GrainAmount, this.LiveStockAmount, this.WineAmount);
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        flags = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (Hero.MainHero.IsKingdomLeader)
          flags |= IssueBase.PreconditionFlags.MainHeroIsKingdomLeader;
        if (issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          flags |= IssueBase.PreconditionFlags.AtWar;
        if (Clan.PlayerClan.Tier < 1)
          flags |= IssueBase.PreconditionFlags.ClanTier;
        if (Clan.PlayerClan.Kingdom != issueGiver.MapFaction)
          flags |= IssueBase.PreconditionFlags.NotInSameFaction;
        return flags == IssueBase.PreconditionFlags.None;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.ClanInfluence ? -0.1f : 0.0f;
      }

      public override bool IssueStayAliveConditions()
      {
        if ((this.IssueOwner.PartyBelongedTo == null || this.IssueOwner.PartyBelongedTo.Army == null || this.IssueOwner.PartyBelongedTo.Army.ArmyOwner != this.IssueOwner || (double) this.IssueOwner.PartyBelongedTo.Army.Cohesion <= 40.0 || this.IssueOwner.Clan == Clan.PlayerClan ? 0 : (this.IssueOwner.MapFaction.IsKingdomFaction ? 1 : 0)) == 0)
          return false;
        this.NumberOfManInArmy = this.IssueOwner.PartyBelongedTo.Army.TotalRegularCount;
        return true;
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class ArmyNeedsSuppliesIssueQuest : QuestBase
    {
      [SaveableField(10)]
      private int _requestedGrainAmount;
      [SaveableField(20)]
      private int _requestedLiveStockAmount;
      [SaveableField(30)]
      private int _requestedWineAmount;
      [SaveableField(40)]
      private int _currentGrainAmount;
      [SaveableField(50)]
      private int _currentLiveStockAmount;
      [SaveableField(60)]
      private int _currentWineAmount;
      [SaveableField(70)]
      private JournalLog _grainLog;
      [SaveableField(80)]
      private JournalLog _liveStockLog;
      [SaveableField(90)]
      private JournalLog _wineLog;

      internal static void AutoGeneratedStaticCollectObjectsArmyNeedsSuppliesIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._grainLog);
        collectedObjects.Add((object) this._liveStockLog);
        collectedObjects.Add((object) this._wineLog);
      }

      internal static object AutoGeneratedGetMemberValue_requestedGrainAmount(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._requestedGrainAmount;
      }

      internal static object AutoGeneratedGetMemberValue_requestedLiveStockAmount(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._requestedLiveStockAmount;
      }

      internal static object AutoGeneratedGetMemberValue_requestedWineAmount(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._requestedWineAmount;
      }

      internal static object AutoGeneratedGetMemberValue_currentGrainAmount(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._currentGrainAmount;
      }

      internal static object AutoGeneratedGetMemberValue_currentLiveStockAmount(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._currentLiveStockAmount;
      }

      internal static object AutoGeneratedGetMemberValue_currentWineAmount(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._currentWineAmount;
      }

      internal static object AutoGeneratedGetMemberValue_grainLog(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._grainLog;
      }

      internal static object AutoGeneratedGetMemberValue_liveStockLog(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._liveStockLog;
      }

      internal static object AutoGeneratedGetMemberValue_wineLog(object o)
      {
        return (object) ((ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest) o)._wineLog;
      }

      public override bool IsRemainingTimeHidden => false;

      public override TextObject Title => new TextObject("{=wVyqTlpS}Army Needs Supply");

      private TextObject _playerStartsQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=GiaTh92Q}{QUEST_GIVER.LINK}, commanding an army of the {QUEST_GIVER_FACTION}, has told you that they need food supplies for their upcoming military campaign. {?QUEST_GIVER.GENDER}She{?}He{\\?} wanted you to deliver {GRAIN_AMOUNT} sacks of grain and although it's not necessary, to provide {LIVESTOCK_AMOUNT} live stocks and {WINE_AMOUNT} barrels of wine {?QUEST_GIVER.GENDER}she{?}he{\\?} would appreciate it.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_GIVER_FACTION", this.QuestGiver.MapFaction.EncyclopediaLinkWithName);
          parent.SetTextVariable("GRAIN_AMOUNT", this._requestedGrainAmount);
          parent.SetTextVariable("LIVESTOCK_AMOUNT", this._requestedLiveStockAmount);
          parent.SetTextVariable("WINE_AMOUNT", this._requestedWineAmount);
          return parent;
        }
      }

      private TextObject _successQuestLogText
      {
        get
        {
          return new TextObject("{=z9pbB0K5}You have successfully delivered the supplies as requested.");
        }
      }

      private TextObject _failQuestLogText
      {
        get => new TextObject("{=k5HJ3Ld6}You have failed to deliver the supplies in time.");
      }

      private TextObject _questCanceledWarDeclaredLog
      {
        get
        {
          TextObject parent = new TextObject("{=vW6kBki9}Your clan is now at war with {QUEST_GIVER.LINK}'s realm. Your agreement with {QUEST_GIVER.LINK} is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _playerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      public ArmyNeedsSuppliesIssueQuest(
        string questId,
        Hero questGiver,
        CampaignTime duration,
        int rewardGold,
        int grainAmount,
        int liveStockAmount,
        int wineAmount)
        : base(questId, questGiver, duration, rewardGold)
      {
        this._requestedGrainAmount = grainAmount;
        this._requestedLiveStockAmount = liveStockAmount;
        this._requestedWineAmount = wineAmount;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void HourlyTick()
      {
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=64RFlBFr}Very well. Don't worry, all your expenses will be covered.[if:convo_approving][ib:hip] ")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=bGbSbqTG}Have you brought our supplies?")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => this.CalculateAndUpdateRequestedItemsCountInPlayer(false))).BeginPlayerOptions().PlayerOption(new TextObject("{=FmjZfigu}Yes. I have brought your grain, livestock and wine as you requested.")).Condition(new ConversationSentence.OnConditionDelegate(this.CheckIfPlayerCollectedEverything)).NpcLine(new TextObject("{=UjS8JnH5}Splendid. I will never forget your service, my friend.")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.CollectedEverythingConsequence)).CloseDialog().PlayerOption(new TextObject("{=ISOHhXxW}Yes. I have brought your grain and wine as you requested.")).Condition(new ConversationSentence.OnConditionDelegate(this.CheckIfPlayerCollectedGrainWine)).NpcLine(new TextObject("{=1atg831t}Thank you. Your service will be remembered.")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.CollectedGrainAndWineConsequence)).CloseDialog().PlayerOption(new TextObject("{=YbsVaZkb}Yes. I have brought your grain and livestock as you requested.")).Condition(new ConversationSentence.OnConditionDelegate(this.CheckIfPlayerCollectedGrainLiveStock)).NpcLine(new TextObject("{=1atg831t}Thank you. Your service will be remembered.")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.CollectedGrainAndLiveStockConsequence)).CloseDialog().PlayerOption(new TextObject("{=m9a3ZalO}Yes. I have brought your grain as you requested.")).Condition(new ConversationSentence.OnConditionDelegate(this.CheckIfPlayerCollectedGrain)).NpcLine(new TextObject("{=1atg831t}Thank you. Your service will be remembered.")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.CollectedGrainConsequence)).CloseDialog().PlayerOption(new TextObject("{=PAbVhuKi}Not yet. I'm still working on it.")).NpcLine(new TextObject("{=AV5xVGM5}Good. We need them as soon as possible.[if:convo_undecided_open][ib:closed2]")).Consequence(new ConversationSentence.OnConsequenceDelegate(MapEventHelper.OnConversationEnd)).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void CollectedGrainConsequence()
      {
        GainRenownAction.Apply(Hero.MainHero, 2f);
        GainKingdomInfluenceAction.ApplyForGivingFood(Hero.MainHero, this.QuestGiver, 5f);
        this.RelationshipChangeWithQuestGiver = 2;
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, DefaultItems.Grain.Value * this._requestedGrainAmount);
        MobileParty.MainParty.ItemRoster.AddToCounts(DefaultItems.Grain, -this._requestedGrainAmount);
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(DefaultItems.Grain, this._requestedGrainAmount);
        this.CompleteQuestWithSuccess();
        MapEventHelper.OnConversationEnd();
      }

      private void CollectedGrainAndLiveStockConsequence()
      {
        GainRenownAction.Apply(Hero.MainHero, 2f);
        GainKingdomInfluenceAction.ApplyForGivingFood(Hero.MainHero, this.QuestGiver, 5f);
        this.RelationshipChangeWithQuestGiver = 3;
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, DefaultItems.Grain.Value * this._requestedGrainAmount + MBObjectManager.Instance.GetObject<ItemObject>("sheep").Value * this._requestedLiveStockAmount);
        MobileParty.MainParty.ItemRoster.AddToCounts(DefaultItems.Grain, -this._requestedGrainAmount);
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(DefaultItems.Grain, this._requestedGrainAmount);
        this.RemoveLiveStocksFromPlayer();
        this.CompleteQuestWithSuccess();
        MapEventHelper.OnConversationEnd();
      }

      private void CollectedGrainAndWineConsequence()
      {
        GainRenownAction.Apply(Hero.MainHero, 2f);
        GainKingdomInfluenceAction.ApplyForGivingFood(Hero.MainHero, this.QuestGiver, 5f);
        this.RelationshipChangeWithQuestGiver = 4;
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, DefaultItems.Grain.Value * this._requestedGrainAmount + MBObjectManager.Instance.GetObject<ItemObject>("wine").Value * this._requestedLiveStockAmount);
        MobileParty.MainParty.ItemRoster.AddToCounts(DefaultItems.Grain, -this._requestedGrainAmount);
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(DefaultItems.Grain, this._requestedGrainAmount);
        ItemObject itemObject = MBObjectManager.Instance.GetObject<ItemObject>("wine");
        MobileParty.MainParty.ItemRoster.AddToCounts(itemObject, -this._requestedWineAmount);
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(itemObject, this._requestedWineAmount);
        this.CompleteQuestWithSuccess();
        MapEventHelper.OnConversationEnd();
      }

      private void CollectedEverythingConsequence()
      {
        GainRenownAction.Apply(Hero.MainHero, 2f);
        GainKingdomInfluenceAction.ApplyForGivingFood(Hero.MainHero, this.QuestGiver, 8f);
        this.RelationshipChangeWithQuestGiver = 6;
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, DefaultItems.Grain.Value * this._requestedGrainAmount + MBObjectManager.Instance.GetObject<ItemObject>("wine").Value * this._requestedLiveStockAmount + MBObjectManager.Instance.GetObject<ItemObject>("sheep").Value * this._requestedLiveStockAmount);
        MobileParty.MainParty.ItemRoster.AddToCounts(DefaultItems.Grain, -this._requestedGrainAmount);
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(DefaultItems.Grain, this._requestedGrainAmount);
        ItemObject itemObject = MBObjectManager.Instance.GetObject<ItemObject>("wine");
        MobileParty.MainParty.ItemRoster.AddToCounts(itemObject, -this._requestedWineAmount);
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(itemObject, this._requestedWineAmount);
        this.RemoveLiveStocksFromPlayer();
        this.CompleteQuestWithSuccess();
        MapEventHelper.OnConversationEnd();
      }

      private void RemoveLiveStocksFromPlayer()
      {
        int num = this._requestedLiveStockAmount;
        while (num > 0)
        {
          for (int index = 0; index < MobileParty.MainParty.ItemRoster.Count; ++index)
          {
            ItemRosterElement itemRosterElement = MobileParty.MainParty.ItemRoster[index];
            if (!itemRosterElement.IsEmpty)
            {
              ItemObject itemObject = itemRosterElement.EquipmentElement.Item;
              if (itemObject.HasHorseComponent && itemObject.HorseComponent.IsLiveStock)
              {
                if (num >= itemRosterElement.Amount)
                {
                  MobileParty.MainParty.ItemRoster.AddToCounts(itemObject, -itemRosterElement.Amount);
                  num -= itemRosterElement.Amount;
                }
                else
                {
                  MobileParty.MainParty.ItemRoster.AddToCounts(itemObject, -num);
                  num = 0;
                  break;
                }
              }
            }
          }
        }
        this.QuestGiver.PartyBelongedTo.ItemRoster.AddToCounts(MBObjectManager.Instance.GetObject<ItemObject>("meat"), this._requestedLiveStockAmount * 2);
      }

      private bool CheckIfPlayerCollectedGrain()
      {
        return this._currentGrainAmount >= this._requestedGrainAmount;
      }

      private bool CheckIfPlayerCollectedGrainLiveStock()
      {
        return this._currentGrainAmount >= this._requestedGrainAmount && this._currentLiveStockAmount >= this._requestedLiveStockAmount;
      }

      private bool CheckIfPlayerCollectedGrainWine()
      {
        return this._currentGrainAmount >= this._requestedGrainAmount && this._currentWineAmount >= this._requestedWineAmount;
      }

      private bool CheckIfPlayerCollectedEverything()
      {
        return this._currentGrainAmount >= this._requestedGrainAmount && this._currentWineAmount >= this._requestedWineAmount && this._currentLiveStockAmount >= this._requestedLiveStockAmount;
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddLog(this._playerStartsQuestLogText);
        this.CalculateAndUpdateRequestedItemsCountInPlayer();
        this._grainLog = this.AddDiscreteLog(TextObject.Empty, new TextObject("{=yGxjOnYb}Collected Grain Amount"), this._currentGrainAmount, this._requestedGrainAmount);
        this._liveStockLog = this.AddDiscreteLog(TextObject.Empty, new TextObject("{=aIxX2s8n}Collected Livestock Amount (Optional)"), this._currentLiveStockAmount, this._requestedLiveStockAmount);
        this._wineLog = this.AddDiscreteLog(TextObject.Empty, new TextObject("{=ENS8Ig1o}Collected Wine Amount (Optional)"), this._currentWineAmount, this._requestedWineAmount);
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.PlayerInventoryExchangeEvent.AddNonSerializedListener((object) this, new Action<List<(ItemRosterElement, int)>, List<(ItemRosterElement, int)>, bool>(this.OnInventoryExchange));
        CampaignEvents.ArmyDispersed.AddNonSerializedListener((object) this, new Action<Army, Army.ArmyDispersionReason, bool>(this.OnArmyDispersed));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (clan == Clan.PlayerClan && oldKingdom == this.QuestGiver.MapFaction)
        {
          TextObject textObject = new TextObject("{=aQVdW6aC}You have left {QUEST_GIVER_FACTION}. Your agreement with {QUEST_GIVER.LINK} is terminated.");
          textObject.SetTextVariable("QUEST_GIVER_FACTION", this.QuestGiver.MapFaction.EncyclopediaLinkWithName);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
          this.CompleteQuestWithCancel(textObject);
        }
        else
        {
          if (!this.QuestGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
            return;
          this.CompleteQuestWithCancel(this._questCanceledWarDeclaredLog);
        }
      }

      private void OnArmyDispersed(Army army, Army.ArmyDispersionReason reason, bool isPlayersArmy)
      {
        if (army.ArmyOwner != this.QuestGiver)
          return;
        this.AddLog(new TextObject("{=K2gsZOMb}Army is disbanded and your mission was canceled."));
        this.CompleteQuestWithCancel();
      }

      private void OnInventoryExchange(
        List<(ItemRosterElement, int)> purchasedItems,
        List<(ItemRosterElement, int)> soldItems,
        bool isTrading)
      {
        this.CalculateAndUpdateRequestedItemsCountInPlayer();
      }

      private void CalculateAndUpdateRequestedItemsCountInPlayer(bool notifyPlayer = true)
      {
        ItemObject grain = DefaultItems.Grain;
        ItemObject itemObject = MBObjectManager.Instance.GetObject<ItemObject>("wine");
        this._currentGrainAmount = MobileParty.MainParty.ItemRoster.GetItemNumber(grain);
        this._currentLiveStockAmount = MobileParty.MainParty.ItemRoster.NumberOfLivestockAnimals;
        this._currentWineAmount = MobileParty.MainParty.ItemRoster.GetItemNumber(itemObject);
        if (notifyPlayer)
        {
          if (this._currentGrainAmount >= this._requestedGrainAmount && this._currentLiveStockAmount >= this._requestedLiveStockAmount && this._currentWineAmount >= this._requestedWineAmount)
            MBInformationManager.AddQuickInformation(new TextObject("{=uEV6kKdU}You have collected all the supplies that the army commander requested. Return to army and deliver the supplies"));
          else if (this._currentGrainAmount >= this._requestedGrainAmount)
            MBInformationManager.AddQuickInformation(new TextObject("{=8XpTvx1i}You have collected enough grains that the army commander requested. Return to army and deliver the supplies"));
        }
        this._currentGrainAmount = (int) MathF.Clamp((float) this._currentGrainAmount, 0.0f, (float) this._requestedGrainAmount);
        this._currentLiveStockAmount = (int) MathF.Clamp((float) this._currentLiveStockAmount, 0.0f, (float) this._requestedLiveStockAmount);
        this._currentWineAmount = (int) MathF.Clamp((float) this._currentWineAmount, 0.0f, (float) this._requestedWineAmount);
        this._grainLog?.UpdateCurrentProgress(this._currentGrainAmount);
        this._liveStockLog?.UpdateCurrentProgress(this._currentLiveStockAmount);
        this._wineLog?.UpdateCurrentProgress(this._currentWineAmount);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this._playerDeclaredWarQuestLogText, this._questCanceledWarDeclaredLog);
      }

      public override void OnFailed() => this.RelationshipChangeWithQuestGiver = -2;

      protected override void OnCompleteWithSuccess() => this.AddLog(this._successQuestLogText);

      protected override void OnTimedOut()
      {
        this.OnFailed();
        this.AddLog(this._failQuestLogText);
      }

      public override void OnCanceled()
      {
      }
    }

    public class ArmyNeedsSuppliesIssueTypeDefiner : SaveableTypeDefiner
    {
      public ArmyNeedsSuppliesIssueTypeDefiner()
        : base(585800)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssue), 1);
        this.AddClassDefinition(typeof (ArmyNeedsSuppliesIssueBehavior.ArmyNeedsSuppliesIssueQuest), 2);
      }
    }
  }
}
